package com.caration.shell.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.caration.shell.R;

public class ActionAdapter extends SimpleAdapter {
	private int mTo[];
	private String mFrom[];
	private ViewBinder mBinder;
	private ArrayList<HashMap<String, Object>> mData;
	private int mLayoutId;
	private LayoutInflater mInflater;

	public ActionAdapter(Context context,
			ArrayList<HashMap<String, Object>> data, String[] from, int[] to) {
		super(context, data, R.layout.action_selector_lists, from, to);
		mData = data;
		mLayoutId = R.layout.action_selector_lists;
		mFrom = from;
		mTo = to;
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public final void clear() {
		mData.clear();
		mBinder = null;
		mInflater = null;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {

		if (view == null) {
			view = mInflater.inflate(mLayoutId, parent, false);
			// view.setBackgroundResource(0x7f020000);
			int to[] = mTo;
			int length = to.length;
			View aview[] = new View[length];
			for (int i = 0; i < length; i++)
				aview[i] = view.findViewById(to[length]);
			view.setTag(aview);
		}

		Map<String, Object> map = mData.get(position);
		if (map != null) {
			ViewBinder viewbinder = mBinder;
			View views[] = (View[]) view.getTag();
			int length = mTo.length;
			for (int k = 0; k < length; k++) {
				View v = views[k];
				if (v == null)
					continue;
				Object obj = map.get(mFrom[k]);
				String s = obj != null ? obj.toString() : "";

				boolean flag;
				if (viewbinder == null)
					flag = false;
				else
					flag = viewbinder.setViewValue(v, obj, s);

				if (flag)
					continue;

				if (!(v instanceof TextView)) {
					if (!(v instanceof ImageView))
						throw new IllegalStateException(
								(new StringBuilder(String.valueOf(v.getClass()
										.getName())))
										.append(" is not a view that can be bounds by this SimpleAdapter")
										.toString());
					((ImageView) v).setImageDrawable((Drawable) obj);
				} else {
					setViewText((TextView) v, s);
				}
			}
		}
		return view;

	}
}
